﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Security;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("sys/organization")]
	public class Sys_OrganizationController : MyBaseController
	{
		private readonly IServiceSysOrganization service;
		private readonly IServiceSysAttachment serviceSysAttachment;
		private VM_RelatedModule[] relatedModules;

		public Sys_OrganizationController(IServiceSysOrganization _service,
			IServiceSysAttachment _serviceSysAttachment,
			ILogger<Sys_OrganizationController> _logger) : base(_logger)
		{
			service = _service;
			serviceSysAttachment = _serviceSysAttachment;
			relatedModules = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				}
			};
		}

		private VMS_Sys_Organization GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_Sys_Organization();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.type = TextHelper.GetIntNullable(paras, "type");
			vm.areaid = TextHelper.GetIntNullable(paras, "areaid");
			vm.state = TextHelper.GetIntNullable(paras, "state");
			vm.pid = TextHelper.GetIntNullable(paras, "pid");
			vm.name = TextHelper.GetString(paras, "name");
			vm.code = TextHelper.GetString(paras, "code");
			vm.chargeman = TextHelper.GetString(paras, "chargeman");
			vm.chargemanphone = TextHelper.GetString(paras, "chargemanphone");
			vm.adddate_s = TextHelper.GetDateTimeStart(paras, "adddate_s");
			vm.adddate_e = TextHelper.GetDateTimeEnd(paras, "adddate_e");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}

		private VMS_Sys_Organization GetSearchModelFromGetRequest()
		{
			var vm = new VMS_Sys_Organization();
			vm.pnum = TextHelper.GetInt(Request.Query["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Query["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Query["sortorder"]);

			vm.areaid = TextHelper.GetIntNullable(Request.Query["areaid"]);
			vm.state = TextHelper.GetIntNullable(Request.Query["state"]);
			vm.pid = TextHelper.GetIntNullable(Request.Query["pid"]);
			vm.name = TextHelper.GetString(Request.Query["name"]);
			vm.code = TextHelper.GetString(Request.Query["code"]);
			vm.chargeman = TextHelper.GetString(Request.Query["chargeman"]);
			vm.chargemanphone = TextHelper.GetString(Request.Query["chargemanphone"]);
			vm.adddate_s = TextHelper.GetDateTimeStart(Request.Query["adddate_s"]);
			vm.adddate_e = TextHelper.GetDateTimeEnd(Request.Query["adddate_e"]);
			vm.ids = TextHelper.GetInts(Request.Query["ids"]);
			return vm;
		}

		private VMS_Sys_Organization GetSearchModelFromPostRequest()
		{
			var vm = new VMS_Sys_Organization();
			vm.pnum = TextHelper.GetInt(Request.Form["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Form["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Form["sortorder"]);

			vm.areaid = TextHelper.GetIntNullable(Request.Form["areaid"]);
			vm.state = TextHelper.GetIntNullable(Request.Form["state"]);
			vm.pid = TextHelper.GetIntNullable(Request.Form["pid"]);
			vm.name = TextHelper.GetString(Request.Form["name"]);
			vm.code = TextHelper.GetString(Request.Form["code"]);
			vm.chargeman = TextHelper.GetString(Request.Form["chargeman"]);
			vm.chargemanphone = TextHelper.GetString(Request.Form["chargemanphone"]);
			vm.adddate_s = TextHelper.GetDateTimeStart(Request.Form["adddate_s"]);
			vm.adddate_e = TextHelper.GetDateTimeEnd(Request.Form["adddate_e"]);
			vm.ids = TextHelper.GetInts(Request.Form["ids[]"]);
			return vm;
		}

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			ViewBag.ServiceCode = "796121046B";
			ViewBag.StateOptions = GetEnums(typeof(OrganizationState));
			ViewBag.TypeOptions = GetEnums(typeof(OrganizationType));
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			return View();
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				PageData pageData = service.GetDetailPageList(searchModel);

				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("add")]
		public IActionResult Add()
		{
			ViewBag.ServiceCode = "796121046B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.TypeOptions = GetEnums(typeof(OrganizationType));
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			//ViewBag.RoleOptions = serviceSysRole.GetRoleSelectListItems();

			Sys_Organization vm = new Sys_Organization
			{
				Code = Guid.NewGuid().ToString("N")
			};
			return View("Edit", vm);
		}

		[ValidateSession]
		[HttpGet("edit/{id}")]
		[HttpGet("edit")]
		public IActionResult Edit(string id)
		{
			ViewBag.ServiceCode = "796121046B";
			ViewBag.RelatedModules = relatedModules;
			ViewBag.TypeOptions = GetEnums(typeof(OrganizationType));
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = service.Get(rowID, sessionCurrent);

				//ViewBag.RoleOptions = serviceSysRole.GetRoleSelectListItems(vm.RolesID);

				return View(vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				return new JsonResultBase(false, "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("save")]
		public IActionResult Save([FromBody] Sys_Organization model)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = service.AddOrUpdate(model, sessionCurrent);

				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "保存失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取指定机构信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "796121046B";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				int rowID = TextHelper.GetInt(id);

				UserSession sessionCurrent = GetSessionFromRequest();

				var vm = service.Get(rowID, sessionCurrent);
				return View("View", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取指定机构信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");

				UserSession sessionCurrent = GetSessionFromRequest();
				var model = service.Get(id, sessionCurrent);

				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public IActionResult Delete([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody] int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.BatchDelete(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("audit")]
		public IActionResult Audit([FromBody] JObject obj)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				int id = TextHelper.GetInt(obj, "id");
				int state = TextHelper.GetInt(obj, "state");
				string remark = obj.Value<string>("remark");

				bool success = service.Audit(id, state, remark, sessionCurrent);

				return new JsonResultBase(success, success ? "成功" : "审核失败");
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("export")]
		public IActionResult Export(JObject obj)
		{
			//context.Response.ContentType = "application/vnd.ms-excel";
			//context.Response.Charset = "UTF-8";
			//context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
			//context.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}_{1}.xls", HttpUtility.UrlEncode(Title), DateTime.Now.ToString("yyyyMMdd_HHmmss")));
			//switch (context.Request.QueryString["all"])
			//return File(byte)
			throw new NotImplementedException();
		}

		/// <summary>
		/// 获取单位编号
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("gencode")]
		public IActionResult GenCode([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");
				string areaCode = TextHelper.GetString(paras, "areacode");
				int areaID = TextHelper.GetInt(paras, "areaid");

				UserSession sessionCurrent = GetSessionFromRequest();
				var result = service.GenCode(areaCode, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("poplist")]
		public IActionResult PopList(string callback, string pid)
		{
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "popOrgCallback" : callback;
			var conditions = new VMS_Sys_Organization();
			if (!string.IsNullOrEmpty(pid))
			{
				var parentID = TextHelper.GetInt(pid);
				conditions.pid = parentID;
			}
			ViewData["conditions"] = TextHelper.SerializeObject(conditions);
			return View();
		}

		[ValidateSession]
		[HttpPost("import")]
		public IActionResult ImportExcelDo()
		{
			string callback = Request.Form["callback"];
			try
			{
				if (Request.Form.Files == null || Request.Form.Files.Count == 0)
				{
					throw new BuzException("请选择要上传的文件");
				}
				IFormFile file = Request.Form.Files[0];
				if (file.Length == 0)
				{
					throw new BuzException("不能上传空文件");
				}
				string fileExt = Path.GetExtension(file.FileName);
				if (Array.IndexOf(new string[] { ".xls", ".xlsx" }, fileExt) < 0)
				{
					throw new BuzException("不支持该文件格式");
				}

				UserSession sessionCurrent = GetSessionFromRequest();

				string fileName = IDGenerator.NextRand32(sessionCurrent.SessionType, sessionCurrent.SessionID) + fileExt;
				string fileDir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/upload/tmp");
				if (!Directory.Exists(fileDir))
				{
					Directory.CreateDirectory(fileDir);
				}
				string filePath = Path.Combine(fileDir, fileName);
				using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
				{
					file.CopyTo(fs);
				}

				var result = service.BatchImport(filePath, sessionCurrent);
				JsonResultBase ret = new JsonResultBase(result);
				return ret;
			}
			catch (AuthException ex)
			{
				logger.LogError(ex, "解析请求头部验证信息出错");
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
				}
				else
				{
					ResultData ret = new ResultData(false, ex.Message);
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
			catch (BuzException ex)
			{
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, ex.Message);
				}
				else
				{
					ResultData ret = new ResultData(false, ex.Message);
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "导入Excel文件出错");
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, "上传失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
				}
				else
				{
					ResultData ret = new ResultData(false, "上传失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
		}

		[ValidateSession]
		[HttpGet("import")]
		public ActionResult ImportExcel(string callback)
		{
			ViewBag.Title = "导入单位信息";
			ViewBag.UploadUrl = Url.Action("ImportExcelDo");
			ViewBag.TplUrl = Url.Content("~/tpl/单位导入模板.xlsx");
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "orgImportCallback" : callback;
			return View();
		}

		[ValidateSession]
		[HttpPost("childlist")]
		public IActionResult GetChildList([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");
				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.GetChildList(id, sessionCurrent);

				return new JsonResultPage(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "获取下级列表失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("ztree")]
		public IActionResult ZTree(string callback)
		{
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "popOrgCallback" : callback;
			return View();
		}

		[HttpPost("ztree")]
		public IActionResult GetZTreeData([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int id = TextHelper.GetInt(paras, "id");

				var result = service.GetZTreeData(id);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}
	}
}